package operation;

import Medicine.Pharmacy;

import java.sql.*;

public class ShowAllMedicine implements IOPeration{
    @Override
    public void work(Pharmacy pharmacy) throws SQLException {
        System.out.println("展示药品信息！");


        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try{
            // 加载并注册数据库驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 通过DriverManager类获取数据库连接
            String url = "jdbc:mysql://localhost:3306/data";
            String username = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url,username, password);
            // 通过Connection对象获取Statement对象
            stmt = conn.createStatement();

            // 执行SQL语句
            String sql = "SELECT * FROM medicine";
            rs = stmt.executeQuery(sql);

            // 操作ResultSet结果集
            System.out.println("id  |  name  |  type  |  price  |  amount  |  ManufactureDate  |  BestDate  ");
            while (rs.next()) {
                int id = rs.getInt("Id");    // 通过列名获取指定字段的值
                String name = rs.getString("Name");
                String type = rs.getString("Type");
                float price = rs.getFloat("Price");
                int amount = rs.getInt("Amount");
                String ManufactureDate = rs.getString("ManufactureDate");
                int BestDate = rs.getInt("BestDate");

                System.out.println(id+"  |  "+name+"  |  "+type+"  |  "+price+"  |  "+amount+"  |  "+ManufactureDate+"  |  "+BestDate+"  ");
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接，释放资源
            if(rs !=null){ rs.close(); }
            if(stmt !=null){ stmt.close(); }
            if(conn !=null){ conn.close(); }
        }
    }
        /*int currSize = pharmacy.getUsedSize();
        for (int i = 0; i < currSize; i++) {
            // 1
            Goods goods = pharmacy.getMedicines(i);
            System.out.println(goods);
        }*/
}
